package sites.manager.common.kit;

import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;

import org.springframework.validation.BindException;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

@RestControllerAdvice
public class GlobalControllerAdvice {

	// 1 处理 form data方式调用接口校验失败抛出的异常
	@ExceptionHandler(BindException.class)
	public Ret bindExceptionHandler(BindException e) {
		e.printStackTrace();
		List<FieldError> fieldErrors = e.getBindingResult().getFieldErrors();
		List<String> collect = fieldErrors.stream().map(o -> o.getDefaultMessage()).collect(Collectors.toList());

		return Ret.fail().setMsg(collect.toString());
	}

	// 2 处理 json 请求体调用接口校验失败抛出的异常
	@ExceptionHandler(MethodArgumentNotValidException.class)
	public Ret methodArgumentNotValidExceptionHandler(MethodArgumentNotValidException e) {
		List<FieldError> fieldErrors = e.getBindingResult().getFieldErrors();
		List<String> collect = fieldErrors.stream().map(o -> o.getDefaultMessage()).collect(Collectors.toList());
		return Ret.fail().setMsg(collect.get(0));
	}

	// 3 处理单个参数校验失败抛出的异常
	@ExceptionHandler(ConstraintViolationException.class)
	public Ret constraintViolationExceptionHandler(ConstraintViolationException e) {
		Set<ConstraintViolation<?>> constraintViolations = e.getConstraintViolations();
		List<String> collect = constraintViolations.stream().map(o -> o.getMessage()).collect(Collectors.toList());
		return Ret.fail().setMsg(collect.get(0));
	}
	
	// 处理其他类异常
	@ExceptionHandler(Exception.class)
	public Ret otherExceptionHandler(Exception e) {
		e.printStackTrace();
		return Ret.fail().setMsg("操作异常");
	}

}
